//
//  KKScanningViewController.m
//  FreightAssistant
//
//  Created by leo on 15/11/12.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "KKScanningViewController.h"

#import <AVFoundation/AVFoundation.h>

@interface KKScanningViewController () <AVCaptureMetadataOutputObjectsDelegate> {
    
    BOOL _isReading;
    AVCaptureSession *_captureSession;
    
    AVCaptureVideoPreviewLayer *_videoPreviewLayer;
}

@end

@implementation KKScanningViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
    
    if (device == nil) {
        return;
    }
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //    output.rectOfInterest = CGRectMake(0.5, 0, 0.5, 1);
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    
    //初始化链接对象
    _captureSession = [[AVCaptureSession alloc]init];
    //高质量采集率
    [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
    
    [_captureSession addInput:input];
    [_captureSession addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession: _captureSession];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
    self.navigationItem.title = @"扫描快递单号";
    
    [_captureSession startRunning];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Public methods
- (void)startScanning:(KKScanningResultHandle)handle {
    
    _resultHandle = [handle copy];
    
    //开始捕获
    [_captureSession startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate methods

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
        NSString *result = metadataObject.stringValue;
        if (result && _resultHandle) {
            [_captureSession stopRunning];
            _resultHandle(result);
            [self.navigationController popViewControllerAnimated: true];
        }
    }
}

@end
